package com.example.myfirstapp;

import java.io.IOException;
import java.util.Calendar;
import java.util.List;
import java.util.Locale;

import com.services.weather.RetrieveWeather;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.RingtoneManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.PowerManager;
import android.text.Html;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class AlarmReceiverActivity extends Activity {
	private static MediaPlayer mMediaPlayer; 
	private PowerManager.WakeLock wl;
	private SharedPreferences sharedPref;
	
	private LocationManager locationManager;
	private Handler mHandler;
	private TextView mAddress;
	private String mAddressText;
	private TextView mWeather;
	private boolean mGeocoderAvailable;
	private Button alarm;
    // UI handler codes.
    private static final int UPDATE_ADDRESS = 1;
    private static final int UPDATE_LATLNG = 2;
    private static final int UPDATE_WEATHER = 3;
    private static final int UPDATE_ALARM = 4;
    
    private static final int TEN_SECONDS = 10000;
    private static final int TEN_METERS = 10;
    private static final int TWO_MINUTES = 1000 * 60 * 2;


	
	@SuppressLint("NewApi")
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        sharedPref = this.getSharedPreferences(getString(R.string.prefFileName), Context.MODE_PRIVATE);
        
        setPowerManager();
        
        // The isPresent() helper method is only available on Gingerbread or above.
        mGeocoderAvailable =
                Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD && Geocoder.isPresent();

        
        //take control of device in most situations
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);
        this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN | 
        	    WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD | 
        	    WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED | 
        	    WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON,
        	    WindowManager.LayoutParams.FLAG_FULLSCREEN | 
        	    WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD | 
        	    WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED | 
        	    WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);
        
        setContentView(R.layout.alarm);
        alarm = (Button) findViewById(R.id.stopAlarm);
        mAddress = (TextView) findViewById(R.id.address);
        mWeather = (TextView) findViewById(R.id.weather);
        mAddressText = "";

        // Get access to network and request weather update
        // String testUrl = "http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20geo.places%20where%20text=\"keller,%20tx\"";
            
    }
 
	protected void onStart() {
		super.onStart();
        alarm.setOnClickListener(new OnClickListener() {
            public void onClick(View arg0) {
                mMediaPlayer.stop();
            	alarm.setText("Stopped");
                //finish();
                
            }
        });
     // Handler for updating text fields on the UI like the address.
       mHandler = new Handler() {
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case UPDATE_ADDRESS:
                        mAddress.setText((String) msg.obj);
                        mAddressText = (String) msg.obj;
                        
                        if (!"No location".equals(mAddressText) && !"".equals(mAddressText)) {
                        	mAddressText = mAddressText.replaceAll(" ", "%20");
                        	String testUrl = "http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20geo.places%20where%20text=\"" + mAddressText + "\"";
                        	
                        	Log.d("YahooWeather", testUrl);
                	        ConnectivityManager connMgr = (ConnectivityManager) 
                	                getSystemService(Context.CONNECTIVITY_SERVICE);
                	            NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
                	            if (networkInfo != null && networkInfo.isConnected()) {
                	            	new WeatherSpin().execute(testUrl);
                	            	
                	            }
                	            else
                	            	Log.d("Network", "Network connection failed");
                        }
                        else {
                        	//setAlarmListener();
                        	//Toast.makeText(this, "Problem with location: " + addressText, Toast.LENGTH_LONG).show();
                        	playSound(getAlarmUri());
                        }
                        
                        break;
                 /*   case UPDATE_LATLNG:
                    	mAddress.setText((String) msg.obj);
                    	break;
                 */
                }
            }
        };
        
        // Get handle to current location
        locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
        
        Location networkLocation = requestUpdatesFromProvider(LocationManager.NETWORK_PROVIDER, R.string.not_support_network);

        if (networkLocation != null)
        	updateUILocation(networkLocation);
        else {
        	mAddress.setText("No location");
        	Log.d("LocationService", "location could not be found");
        }
	}
	
	protected void onRestart() {
		super.onRestart();
		setPowerManager();
	}
	protected void onStop() {
        super.onStop();
        wl.release();
        mMediaPlayer.stop();
        locationManager.removeUpdates(listener);
        finish();
    }
	
    private Location requestUpdatesFromProvider(final String provider, final int errorResId) {
        Location location = null;
        if (locationManager.isProviderEnabled(provider)) {
            //locationManager.requestLocationUpdates(provider, TEN_SECONDS, TEN_METERS, listener);
            location = locationManager.getLastKnownLocation(provider);
        } else {
            Toast.makeText(this, errorResId, Toast.LENGTH_LONG).show();
        }
        return location;
    }
	// Listen for location updates
	private final LocationListener listener = new LocationListener() {

	        @Override
	        public void onLocationChanged(Location location) {
	            // A new location update is received.  Do something useful with it.  Update the UI with
	            // the location update.
	            updateUILocation(location);
	        }

	        @Override
	        public void onProviderDisabled(String provider) {
	        }

	        @Override
	        public void onProviderEnabled(String provider) {
	        }

	        @Override
	        public void onStatusChanged(String provider, int status, Bundle extras) {
	        }
	};
	    
    private void updateUILocation(Location location) {
        // We're sending the update to a handler which then updates the UI with the new
        // location.
        //Message.obtain(mHandler, UPDATE_LATLNG, location.getLatitude() + ", " + location.getLongitude()).sendToTarget();

        // Bypass reverse-geocoding only if the Geocoder service is available on the device.
        if (mGeocoderAvailable) {
        	doReverseGeocoding(location);
        	
        	try {
        		Thread.sleep(5000);
        	} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
        }
    }
    
    private void doReverseGeocoding(Location location) {
        // Since the geocoding API is synchronous and may take a while.  You don't want to lock
        // up the UI thread.  Invoking reverse geocoding in an AsyncTask.
        (new ReverseGeocodingTask(this)).execute(new Location[] {location});
    }

 
    private void setPowerManager() {
    	// get access to device power management
        PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
        wl = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK, "My Tag");
        wl.acquire();
    }
    
    private void playSound(Uri alert) {
    	
        mMediaPlayer = new MediaPlayer();
        try {
            mMediaPlayer.setDataSource(this, alert);
            final AudioManager audioManager = (AudioManager) this
                    .getSystemService(Context.AUDIO_SERVICE);
            if (audioManager.getStreamVolume(AudioManager.STREAM_ALARM) != 0) {
                mMediaPlayer.setAudioStreamType(AudioManager.STREAM_ALARM);
               mMediaPlayer.prepare();
               //Commented out for testing silently
               mMediaPlayer.start();

            }
        } catch (IOException e) {
            System.out.println("OOPS");
        }
        
        alarm.setText("Alarming");
       Log.d("SystemAlarm", "Alarm sounding");
    }
 
        //Get an alarm sound. Try for an alarm. If none set, try notification, 
        //Otherwise, ringtone.
    private Uri getAlarmUri() {
        Uri alert = RingtoneManager
                .getDefaultUri(RingtoneManager.TYPE_ALARM);
        if (alert == null) {
            alert = RingtoneManager
                    .getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
            if (alert == null) {
                alert = RingtoneManager
                        .getDefaultUri(RingtoneManager.TYPE_RINGTONE);
            }
        }
        return alert;
    }
    
    // Get weather updates from Yahoo in separate thread
    @SuppressWarnings("rawtypes")
	private class WeatherSpin extends AsyncTask<String, String, RetrieveWeather> {

		@Override
		protected RetrieveWeather doInBackground(String... urls) {
			
			String url = urls[0];
			
			RetrieveWeather weather = new RetrieveWeather(url);
			return weather;
		}
    	
		 @Override
		    protected void onPostExecute(RetrieveWeather result) {
			
			 int alarmSnooze = 0;
			 /* Check if alarm has already snoozed */
			 if(!sharedPref.getBoolean(getString(R.string.saved_hasSnooze), false))
				 alarmSnooze = findWeatherDelay(result.getForecastCode());
		     
			 if (alarmSnooze > 0) {
				 //setContentView(R.layout.activity_main);
				 Calendar curCal = setSystemAlarm(alarmSnooze);
				 alarm.setText("Snoozing");
			     //EditText currentAlarm = (EditText) findViewById(R.id.curAlarmText);
			     //currentAlarm.setText(curCal.getTime().toString());
				 
			 }
			 else {
			     //setContentView(R.layout.alarm);
				 mWeather.setText(Html.fromHtml(result.getDescription()));
			    // Message.obtain(mHandler, UPDATE_WEATHER, result.getDescription()).sendToTarget();
			     //setAlarmListener();
				 playSound(getAlarmUri());
			 }
		    }
    }
/*
    private void setAlarmListener() {
    	
        alarm.setOnClickListener(new OnClickListener() {
            public void onClick(View arg0) {
                //mMediaPlayer.stop();
            	alarm.setText("Stopped");
                finish();
                
            }
        });
    }
*/
    // Get human readable location in separate thread
    private class ReverseGeocodingTask extends AsyncTask<Location, Void, Void> {
        Context mContext;

        public ReverseGeocodingTask(Context context) {
            super();
            mContext = context;
        }

        @Override
        protected Void doInBackground(Location... params) {
            Geocoder geocoder = new Geocoder(mContext, Locale.getDefault());

            Location loc = params[0];
            List<Address> addresses = null;
            try {
                addresses = geocoder.getFromLocation(loc.getLatitude(), loc.getLongitude(), 1);
            } catch (IOException e) {
                e.printStackTrace();
                // Update address field with the exception.
                Message.obtain(mHandler, UPDATE_ADDRESS, e.toString()).sendToTarget();
            }
            if (addresses != null && addresses.size() > 0) {
                Address address = addresses.get(0);
                // Format the first line of address (if available), city, and country name.
                String addressText = String.format("%s %s",
                        address.getLocality(),
                        address.getAdminArea());
                // Update address field on UI.
                Message.obtain(mHandler, UPDATE_ADDRESS, addressText).sendToTarget();
            }
            return null;
        }
    }
    
    // determine if alarm should snooze based on weather
    private int findWeatherDelay(String code) {
    	int delay = 0;
    	int weatherCode = Integer.parseInt(code);
    	/* 0-18, 35, 37-47 is bad weather - wake up immediately
    	 * 19-34 is decent weather - snooze alarm */
    	if (weatherCode <= 18 || weatherCode == 35)
    		delay = 0;
    	else if (weatherCode >= 37 && weatherCode <= 47)
    		delay = 0;
    	else
    		//delay = 1; //testing only
    		delay = 15;
    	
    	return delay;
    }
    
    // Sets the alarm
    private Calendar setSystemAlarm(int minutesToDelay) {
    	//Create an offset from the current time in which the alarm will go off.
    	
    	// retrieve earliest alarm time from preferences
        
    	String minTime = sharedPref.getString(getString(R.string.saved_curtime), "");
    	Log.d("SystemAlarm", "Earliest time retrieved from prefs:" + minTime);
    	int minutes = 0;
    	int hours = 0;
    	int minuteIndex = minTime.indexOf(",");
    	
    	minutes = Integer.parseInt(minTime.substring(minuteIndex + 1));
    	hours = Integer.parseInt(minTime.substring(0,minuteIndex));
    	Log.d("SystemAlarm", "Hours from saved pref: " + hours + ", Minutes: " + minutes);
    	// add delay to alarm
    	minutes += minutesToDelay;
    	
        Calendar cal = Calendar.getInstance();
        cal.set(Calendar.HOUR_OF_DAY, hours);
        cal.set(Calendar.MINUTE, minutes);
        Log.d("SystemAlarm", "Snoozing alarm until: " + cal.getTime().toString());
        //Create a new PendingIntent and add it to the AlarmManager
        Intent intent = new Intent(this, AlarmReceiverActivity.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(this,
            12345, intent, PendingIntent.FLAG_CANCEL_CURRENT);
        AlarmManager am = 
            (AlarmManager)getSystemService(Activity.ALARM_SERVICE);
        am.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(),
                pendingIntent);
        
        // Save new alarm time
        String time = "";
        time = cal.get(Calendar.HOUR_OF_DAY) + "," + cal.get(Calendar.MINUTE);
        SharedPreferences.Editor editor = sharedPref.edit();
        editor.putString(getString(R.string.saved_curtime), time);
        editor.commit();
        editor.putBoolean(getString(R.string.saved_hasSnooze), true);
        editor.commit();
        
        return cal;
    }
}
